package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"golang.org/x/sys/windows/registry"
)

var logger *log.Logger

func init() {
	logFile, err := os.OpenFile("installLog.txt", os.O_RDWR|os.O_CREATE, 0777)
	if err != nil {
		fmt.Printf("open file error=%s\r\n", err.Error())
		os.Exit(-1)
	}

	// defer logFile.Close()
	// logger = log.New(logFile, "\r\n", log.Ldate|log.Ltime|log.Llongfile)
	logger = log.New(logFile, "\r\n", log.Ldate|log.Ltime|log.Lshortfile)
}
func regKey(path string) error {
	logger.Println("start register")
	vconsoleKey, ok, err := registry.CreateKey(registry.CLASSES_ROOT, `ceeloConsole`, registry.CREATE_SUB_KEY|registry.SET_VALUE)
	if err != nil {
		logger.Printf("CreateKey console err :%v\n", err)
		return err
	}
	if ok {
		return err
	}
	defer vconsoleKey.Close()
	vconsoleKey.SetStringValue("URL Protocol", "")
	// 要检测执行文件当前目录
	vconsoleKey.SetStringValue("DefaultIcon", path)
	shellKey, _, err := registry.CreateKey(vconsoleKey, `shell`, registry.CREATE_SUB_KEY)
	if err != nil {
		logger.Printf("CreateKey shell err :%v\n", err)
		return err
	}
	openKey, _, err := registry.CreateKey(shellKey, `open`, registry.CREATE_SUB_KEY)
	if err != nil {
		logger.Printf("CreateKey open err :%v\n", err)
		return err
	}
	commandKey, _, err := registry.CreateKey(openKey, `command`, registry.CREATE_SUB_KEY|registry.SET_VALUE)
	if err != nil {
		logger.Printf("CreateKey err :%v\n", err)
		return err
	}
	commandKey.SetStringValue("", path)

	return nil
}

// 不能成功，总提示权限不够
func cancleReg() {

	err := registry.DeleteKey(registry.CLASSES_ROOT, `ceeloConsole`)
	if err != nil {
		logger.Println("Clean Reg Err:", err)
		return
	}
	logger.Println("clear ok!")
}
func fixReg(name string) (err error) {
	k, err := registry.OpenKey(registry.CLASSES_ROOT, "ceeloConsole", registry.ALL_ACCESS)
	defer k.Close()
	if err != nil {
		logger.Println(err)
		return
	}
	k.SetStringValue("DefaultIcon", name)
	sk, err := registry.OpenKey(k, "shell", registry.ALL_ACCESS)
	if err != nil {
		return
	}
	ok, err := registry.OpenKey(sk, "open", registry.ALL_ACCESS)
	if err != nil {
		return
	}
	ck, err := registry.OpenKey(ok, "command", registry.ALL_ACCESS)
	if err != nil {
		return
	}
	ck.SetStringValue("", name)
	return
}
func main() {
	initName := `C:\ceelo` + `\` + `ceeloConsole.exe`
	n := flag.String("path", initName, "安装的路径")
	flag.Parse()
	name := *n
	logger.Println("path", name)
	logger.Printf("RegKey begin:%v\n", name)
	err := fixReg(*n)
	if err != nil {
		logger.Println("fix Reg Err ", err)
		err = regKey(name)
		if err != nil {
			logger.Printf("Write Reg Err:%v\n", err)
			return
		}
	}
	logger.Printf("Register Key Over!\n")
	return
}
